<template>
  <div class="m-iselect">
    <span class="name">
      按省份选择:
    </span>
    <el-select v-model="pvalue" filterable placeholder="省份" @change="changeP">
      <el-option
        v-for="item in province"
        :key="item.value"
        :label="item.label"
        :value="item.value + item.label"
      />
    </el-select>
    <el-select v-model="cvalue" filterable :disabled="!city.length" placeholder="城市" @change="changeC">
      <el-option
        v-for="item in city"
        :key="item.value"
        :label="item.label"
        :value="item.value + item.label"
      />
    </el-select>
    <span class="name" style="margin-left:68px!important;">
      直接搜索:
    </span>
    <el-autocomplete
      v-model="input"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入城市中文或拼音"
      style="width:20%"
      clearable
      @select="handleSelect"
      @input="change"
    />
  </div>
</template>

<script>
/* eslint-disable no-console */
import _ from 'lodash'
import { mapActions } from 'vuex'
import cookies from 'vue-cookies'
import pyjs from 'js-pinyin'
export default {
  data () {
    return {
      pvalue: '',
      cvalue: '',
      province: [],
      city: [],
      input: '',
      cities: [],
      pName: '',
      cName: '',
      search: '',
      citiesByPinYin: []
    }
  },
  watch: {
    async pvalue (newPvalue) {
      const pid = newPvalue.substr(0, 6)
      // eslint-disable-next-line no-console
      console.log(pid)
      const { status, data: { city } } = await this.$axios.get(`/geo/getCityByPid/${pid}`)
      if (status === 200) {
        this.city = city.map((item) => {
          return {
            value: item.id,
            label: item.name
          }
        })
        this.cvalue = ''
      } else {
        this.city = []
      }
    }
  },
  mounted () {
    this.getProvince()
  },
  methods: {
    // 修改vuex中当前位置
    ...mapActions('geo', ['setPosition']), // geo表示是给这个模块下的方法，mapActions对应着模块中的actions
    // 直接搜索城市过滤对应的城市
    querySearchAsync: _.debounce(async function (query, cb) {
      const self = this
      // 判断是否这两个数组已经有值，有值直接过滤
      if (self.cities.length || self.citiesByPinYin.length) {
        // 判断输入的是字母还是文字
        const keyword = query.charCodeAt(0)
        if (keyword > 96 && keyword < 123) {
          // 证明输入的是文字
          // 只截取第一个字母并转换为大写，过滤对应字母的城市
          const newarr = self.citiesByPinYin.filter(item => item.title.includes(query.substr(0, 1).toLocaleUpperCase()))[0].city
          cb(newarr)
        } else {
          // 输入的是中文
          cb(self.cities.filter(item => item.value.includes(query)))
        }
      } else {
        // 全国城市数组没有内容，先发请求获取数据
        const { status, data: { city } } = await self.$axios.get('/geo/getCity')
        if (status === 200) {
          // 对请求的结果做一个筛选重命名处理
          self.cities = city.map((item) => {
            return {
              value: item.name,
              province: item.province
            }
          })
          let p // 用来存储所有城市首字母
          let c // 存储城市首字母的编码值
          const d = {} // 存储对应字母对应城市的对象
          city.forEach((item) => {
            p = pyjs.getFullChars(item.name).toLocaleLowerCase().slice(0, 1) // 获取城市首字母
            c = p.charCodeAt(0)
            if (c > 96 && c < 123) {
              if (!d[p]) {
                d[p] = []
              }
              d[p].push({ value: item.name, province: item.province })
            }
          })
          for (const [k, v] of Object.entries(d)) {
            self.citiesByPinYin.push({
              title: k.toUpperCase(),
              city: v
            })
          }
          console.log(self.citiesByPinYin)
          const keyword = query.charCodeAt(0)
          console.log(keyword)
          if (keyword > 96 && keyword < 123) {
            const newarr = self.citiesByPinYin.filter(item => item.title.includes(query.toLocaleUpperCase()))[0].city
            cb(newarr)
          } else {
            cb(self.cities.filter(item => item.value.includes(query)))
          }
        } else {
          // eslint-disable-next-line standard/no-callback-literal
          cb([])
        }
      }
    }, 200),
    change (e) {
      console.log(e)
    },
    // 获取所有的省份
    async getProvince () {
      const { status, data: { province } } = await this.$axios.get('/geo/getProvince')
      if (status === 200) {
        this.province = province.map((item) => {
          return {
            value: item.id,
            label: item.name
          }
        })
      }
    },
    // 选择省份触发
    changeP (e) {
      // 对返回的数据做截取处理
      this.pName = e.slice(6)
    },
    // 选择城市触发
    changeC (e) {
      // 对返回的数据做截取处理
      this.cName = e.slice(6) === '市辖区' ? this.pName : e.slice(6)
      // 先清除cookies
      cookies.remove('city')
      // 获取local中的历史记录
      const historyCollects = JSON.parse(window.localStorage.getItem('historyCollects')) || []
      // 判断数据中是否已经有该城市
      const index = historyCollects.findIndex(item => item.city === this.cName)
      if (index !== -1) {
        // 证明数据中有该城市
        historyCollects.splice(index, 1)
      }
      historyCollects.unshift({ province: this.pName, city: this.cName })
      // 重新修改vuex中的城市定位
      this.setPosition({
        province: this.pName,
        city: this.cName
      })
      // 把选择的城市存储到cookie中
      cookies.set('city', this.cName)
      // 存回local
      window.localStorage.setItem('historyCollects', JSON.stringify(historyCollects))
      // 跳转到上一个路由位置
      location.href = '/'
    },
    // 直接搜索城市选择时触发
    handleSelect (item) {
      const city = item.value === '市辖区' ? item.province : item.value
      // 先清除cookies
      cookies.remove('city')
      // 获取local中的历史记录
      const historyCollects = JSON.parse(window.localStorage.getItem('historyCollects')) || []
      // 判断数据中是否已经有该城市
      const index = historyCollects.findIndex(item => item.city === city)
      if (index !== -1) {
        // 证明数据中有该城市
        historyCollects.splice(index, 1)
      }
      historyCollects.unshift({
        province: item.province,
        city
      })
      this.setPosition({
        province: item.province,
        city
      })
      cookies.set('city', city)
      // 存回local
      window.localStorage.setItem('historyCollects', JSON.stringify(historyCollects))
      location.href = '/'
    }
  }
}
</script>

<style>

</style>
